package com.atguigu.gmall.all.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.context.IContext;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

/**
 * @author atguigu-mqx
 */
@Controller
public class IndexController {

    //  远程调用product
    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private TemplateEngine templateEngine;

    //  首页控制器
    @GetMapping({"index.html","/"})
    public String index(Model model){
        //  远程调用数据
        Result result = productFeignClient.getBaseCategoryList();

        //  all 这个参数必须是集合Map！很多key； 这个key 正好对应的页面渲染的需要的key！
        //  map.put("skuInfo",skuInfo)   map.put("price",skuPrice)  或者是 实体类！
        //  model.addAllAttributes(result.getData());
        model.addAttribute("list",result.getData());
        return "index/index";
    }


    //  nginx 做静态化处理！ 制作页面数据！
    @GetMapping("createIndex")
    @ResponseBody
    public Result result(){
        //  远程调用数据
        Result result = productFeignClient.getBaseCategoryList();
        //  声明对象
        Context context = new Context();
        context.setVariable("list",result.getData());
        Writer writer = null;
        try {
            writer = new FileWriter("D:\\index.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //  void process(String var1, IContext var2, Writer var3);
        templateEngine.process("index/index.html",context,writer);
        return Result.ok();
    }


}
